import Config from '@/config/index.js'
import Store from '@/store/index.js'
import ApiLogin from '@/api/login.js'

// const whiteList = ['login', '/auth-redirect', '/bind', '/register']

//自定义请求
function request(option){
	const baseUrl = Config.baseUrl + "/app/"
	//
	if(option.isToken != false){
		if(!Store.getToken()){
			return new Promise((resolve, reject) =>{
				reject('未授权，请先登录');
			});
		}
	}
	
	//url添加前缀
	option.url = baseUrl + option.url;
	
	//删除参数属性为null或undefined的属性
	if(option.data){
		for(let o in option.data){
			if(!option.data[o] && option.data[o] != 0)delete option.data[o];
		}
	}		
	
	let header = {};
	//isToken 是否需要token认证
	if(option.isToken != false){
		header['Authorization'] = 'Bearer ' + Store.getToken()	// 让每个请求携带自定义token 请根据实际情况自行修改
	}
	delete option.isToken;
	
	//默认GET请求
	if(!option.method){
		option.method = "GET";
	}
	
	console.log(111)
	console.log(option)
	
	return new Promise((resolve, reject) => {
		uni.request({
			...option,
			header: header,
			success: function(res) {
				console.log(222)
				console.log(res)
				if(res.data.code == 401){
					//登录状态已过期
					ApiLogin.logout();
				} else {
					resolve(res.data);    //返回后端数据
				}
			},
			fail: function(res) {
				// console.log(333)
				// console.log(res)
				reject(res);
			}
		})
	})
}

export default { request }